//
//  ArtDetailViewController.m
//  chanyou
//
//  Created by 高爽 on 15-1-4.
//  Copyright (c) 2015年 wanli. All rights reserved.
//

#import "ArtDetailViewController.h"
#import "ArtDetailTableViewCell.h"
#import "ArtDetailModel.h"
#import "ConnectModel.h"
#import "PicTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "TextTableViewCell.h"
#import "LocTableViewCell.h"
#import "ArticlesDatabase.h"
#import "LoginViewController.h"
#import "Singleton.h"
#import <ShareSDK/ShareSDK.h>
#import "ArticlesModel.h"
#import "AttractionsViewController.h"

#import "Masonry.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface ArtDetailViewController ()<UITableViewDataSource, UITableViewDelegate,ISSShareViewDelegate>


@end

@implementation ArtDetailViewController

- (void)dealloc
{
    [_array release];
    [_locId release];
    [_table release];
    [_name release];
    [_imv release];
    [_reloadImg release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.articles = [[ArticlesModel alloc] init];
        self.array = [NSMutableArray array];
        self.detailId = _detailId;
        self.locId = _locId;
    }return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // self.navigationController.navigationBarHidden = YES;
//    self.navigationController.navigationBar.translucent = YES;

//    self.navigationController.navigationBar.alpha = 0.5;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];

//    [self.navigationItem.rightBarButtonItem setTintColor:[UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1]];
    UIButton *share = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)] autorelease];
    [share setImage:[UIImage imageNamed:@"iconfont-fenxiang-2.png"] forState:UIControlStateNormal];
    [share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];

    

//    UIButton *share = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)] autorelease];
//    [share setImage:[UIImage imageNamed:@"iconfont-fenxiang-2.png"] forState:UIControlStateNormal];
//    [share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
//    
//    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:share] autorelease];

    // navigation的title
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 100)] autorelease];
    label.textColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    label.text = @"专题";
    self.navigationItem.titleView = label;


    // bar上的分享与收藏按钮
    UIBarButtonItem *collectButton = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-shoucang1-2.png"] style:UIBarButtonItemStylePlain target:self action:@selector(collectAction:)]autorelease];
//    UIButton *share = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)] autorelease];
    [share setImage:[UIImage imageNamed:@"iconfont-share.png"] forState:UIControlStateNormal];
    [share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:share] autorelease];


    UIBarButtonItem *shareButton = [[[UIBarButtonItem alloc] initWithCustomView:share] autorelease];
    [self.navigationItem setRightBarButtonItems:[NSMutableArray arrayWithObjects:collectButton, shareButton, nil] animated:YES];
    
    
    self.table = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain] autorelease];
    
    _table.dataSource = self;
    _table.delegate = self;
     _table.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _table.tableHeaderView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREEN_HEIGHT / 3)] autorelease];
    // _table.tableHeaderView.backgroundColor = [UIColor cyanColor];
    
    
    
    // 标题
    self.imv = [[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, SCREEN_HEIGHT / 3)] autorelease];
    [_table.tableHeaderView addSubview:_imv];

    
    self.name = [[[UILabel alloc] initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, 20)] autorelease];
    [_name setTextAlignment:NSTextAlignmentCenter];
    [_name setShadowColor:[UIColor lightGrayColor]];
    [_name setHighlighted:YES];
    [_name setFont:[UIFont systemFontOfSize:25]];
    [_name setTextColor:[UIColor whiteColor]];
    [_table.tableHeaderView addSubview:_name];
    
    self.titleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0, 110, self.view.frame.size.width, 20)] autorelease];
    [_titleLabel setTextColor:[UIColor whiteColor]];
    [_titleLabel setTextAlignment:NSTextAlignmentCenter];
    [_table.tableHeaderView addSubview:_titleLabel];
    
    
    [_table registerClass:[ArtDetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    [_table registerClass:[PicTableViewCell class] forCellReuseIdentifier:@"picCell"];
    [_table registerClass:[TextTableViewCell class] forCellReuseIdentifier:@"textCell"];
    [_table registerClass:[LocTableViewCell class] forCellReuseIdentifier:@"locCell"];
    
    [self.view addSubview:_table];
    
    
    
    // 风火轮
    self.reloadImg = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"reload.png"]] autorelease];
    _reloadImg.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 - 64);
    // _reloadImg.clipsToBounds = YES;
    [self.view addSubview:_reloadImg];
    
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.repeatCount = 10000;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeForwards;
    [_reloadImg.layer addAnimation:rotationAnimation forKey:@"rotation"];
    
    
    [self jsonParser];
    
}

#pragma mark - 
#pragma mark 收藏
- (void)collectAction:(UIButton *)button
{
    Singleton *share = [Singleton shareInstance];
    if ((share.logined == NO || [[share.loginDefault objectForKey:@"登陆状态"] isEqualToString:@"no"])) {
        self.alertCollection = [[UIAlertView alloc] initWithTitle:nil message:@"请先登录后操作" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [_alertCollection show];
        [NSTimer scheduledTimerWithTimeInterval:1.2f target:self selector:@selector(alertCollectionAction:) userInfo:nil repeats:YES];
        
        LoginViewController *loginView = [[[LoginViewController alloc] init] autorelease];
        UINavigationController *nav = [[[UINavigationController alloc] initWithRootViewController:loginView] autorelease];
        nav.navigationBar.translucent = YES;
        NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
        nav.navigationBar.titleTextAttributes = dic;
        
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        
    } else {
        BOOL insertJudge = [ArticlesDatabase insertIntoTravelWithArticlesModel:_articles];
        if (insertJudge == YES) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该专题已经被收藏过!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
            
        }
    }

}

- (void)alertCollectionAction:(id)sender
{
    [_alertCollection dismissWithClickedButtonIndex:1 animated:YES];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArtDetailModel *model = [_array objectAtIndex:indexPath.row];
    if (model.groupPic.length == 0 && ! (model.subTitle.length == 0)) {
        
        ArtDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        [cell.content setText:model.descrip];
        
        [cell.subLabel setText:model.subTitle];
        
        return cell;
    } else if (model.groupPic.length == 0 && model.subTitle.length == 0 ) {
        
        TextTableViewCell *textCell = [tableView dequeueReusableCellWithIdentifier:@"textCell"];
        [textCell.content setText:model.descrip];
        
        return textCell;
    } else if (model.loc) {
        
        LocTableViewCell *locCell = [tableView dequeueReusableCellWithIdentifier:@"locCell"];
        [locCell.loc setTitle:model.loc forState:UIControlStateNormal];
//        [locCell.loc setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSString *path = model.groupPic;
//        [locCell.pic imageWithUrl:path placeHolder:nil];
        [locCell.pic sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed: @"placeHold.png"]];
        [locCell.descrip setText:model.descrip];
        locCell.loc.tag = model.locId;
        [locCell.loc addTarget:self action:@selector(locAction:) forControlEvents:UIControlEventTouchUpInside];
        
        return locCell;
    } else {
    PicTableViewCell *picCell = [tableView dequeueReusableCellWithIdentifier:@"picCell"];
    NSString *path = model.groupPic;
//    [picCell.groupPic imageWithUrl:path placeHolder:nil];
    [picCell.groupPic sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
    [picCell.content setText:model.descrip];
    
    return picCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArtDetailModel *model = [_array objectAtIndex:indexPath.row];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15.0f], NSFontAttributeName, nil];
    CGRect rect = [model.descrip boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 1000) options:(NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading) attributes:dic context:nil];
    if (model.groupPic.length == 0) {
        
        CGFloat height = rect.size.height + 70;
        
        return height;
        
    } else if (!model.loc) {
        CGFloat height = rect.size.height + SCREEN_HEIGHT / 3 + 30;
        return height;
    } else {
        CGFloat height = rect.size.height + SCREEN_HEIGHT / 3 + 70;
        return height;
    }
    // return 240;
}

- (void)jsonParser
{
    self.path = [NSString stringWithFormat:@"http://chanyouji.com/api/articles/%ld.json", (long)_detailId];
    // NSString *path = @"http://chanyouji.com/api/articles/453.json";
    [ConnectModel connectModelWithUrl:_path parmaters:nil finished:^(NSData *data) {
        // 移除风火轮
        [_reloadImg removeFromSuperview];
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        // 大标题
        self.name.text = [dic objectForKey:@"name"];
        // 副标题
        self.titleLabel.text = [dic objectForKey:@"title"];
        // pic
        NSString *pic = [dic objectForKey:@"image_url"];
//        NSURL *url = [NSURL URLWithString:pic];
//        NSMutableData *picData = [NSMutableData dataWithContentsOfURL:url];
//        UIImage *img = [UIImage imageWithData:picData];
        // self.imv.image = img;
//        [self.imv imageWithUrl:pic placeHolder:nil];
        [self.imv sd_setImageWithURL:[NSURL URLWithString:pic] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
        
        
        // 数组: article_sections
        NSMutableArray *secArray = [NSMutableArray array];
        [secArray addObjectsFromArray:[dic objectForKey:@"article_sections"]];
        [secArray removeLastObject];
        for (int i = 0; i < [secArray count]; i++) {
            ArtDetailModel *detail = [[[ArtDetailModel alloc] init] autorelease];
            
            NSMutableDictionary *dSection = [secArray objectAtIndex:i];
            // [dSection removeObjectForKey:@"21"];
            // NSLog( @"21 = %@", [dSection objectForKey:@"21"]);
            detail.descrip = [dSection objectForKey:@"description"];

            
            detail.subTitle = [dSection objectForKey:@"title"];
            detail.groupPic = [dSection objectForKey:@"image_url"];
            
            
            // loc
            NSMutableDictionary *dicLoc = [dSection objectForKey:@"attraction"];
            detail.loc = [dicLoc objectForKey:@"name"];
            
//            NSNumber *num = [dicLoc objectForKey:@"id"];
//            self.locId = [num intValue];
            detail.locId = [[dicLoc objectForKey:@"id"] integerValue];
            NSLog(@"locid = %ld", (long)detail.locId);
            [_array addObject:detail];
            
        }
        
        
        [_table reloadData];
    }];
}
- (void)backAction
{
    NSLog(@"back");
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)shareAction:(id)sender
{
    Singleton *share = [Singleton shareInstance];
    share.loginDefault = [NSUserDefaults standardUserDefaults];
    if ([[share.loginDefault objectForKey:@"登陆状态"] isEqualToString:@"yes"] || share.logined == YES) {
        
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"ShareSDK" ofType:@"png"];
        //构造分享内容
        NSString *str = [_path stringByReplacingOccurrencesOfString:@"/api" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@".json" withString:@""];
        
        id<ISSContent> publishContent = [ShareSDK content:[NSString stringWithFormat:@"我在这里看到一篇游记指南#%@#,%@", _name.text, str] defaultContent:@"测试一下"image:[ShareSDK imageWithPath:imagePath]title:@"ShareSDK" url:@"http://www.mob.com" description:@"这是一条测试信息" mediaType: SSPublishContentMediaTypeNews];
        //创建弹出菜单容器
        id<ISSContainer> container = [ShareSDK container];
        [container setIPadContainerWithView:sender arrowDirect:UIPopoverArrowDirectionUp];
        [container setIPhoneContainerWithViewController:self];
        //自定义标题栏相关委托
        id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                             allowCallback:NO
                                                             authViewStyle:SSAuthViewStyleFullScreenPopup
                                                              viewDelegate:nil
                                                   authManagerViewDelegate:nil];
        //自定义标题栏相关委托
        id<ISSShareOptions> shareOptions = [ShareSDK defaultShareOptionsWithTitle:@"分享"
                                                                  oneKeyShareList:[NSArray defaultOneKeyShareList]
                                                                   qqButtonHidden:YES
                                                            wxSessionButtonHidden:YES
                                                           wxTimelineButtonHidden:YES
                                                             showKeyboardOnAppear:NO
                                                                shareViewDelegate:self
                                                              friendsViewDelegate:nil
                                                            picViewerViewDelegate:nil];
        
        //弹出分享菜单
        [ShareSDK showShareActionSheet:container
                             shareList:nil
                               content:publishContent
                         statusBarTips:YES
                           authOptions:authOptions
                          shareOptions:shareOptions
                                result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                    
                                    if (state == SSResponseStateSuccess)
                                    {
                                        _alert = [[UIAlertView alloc] initWithTitle:@"分享成功" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                                        [_alert show];
                                        [NSTimer scheduledTimerWithTimeInterval:1.2f target:self selector:@selector(alertAction:) userInfo:nil repeats:YES];
                                        
                                    }
                                    else if (state == SSResponseStateFail)
                                    {
                                        _alert = [[UIAlertView alloc] initWithTitle:@"分享失败" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                                        [_alert show];
                                        [NSTimer scheduledTimerWithTimeInterval:1.2f target:self selector:@selector(alertAction:) userInfo:nil repeats:YES];
                                    }
                                }];
    } else {
        self.alterLogin = [[UIAlertView alloc] initWithTitle:@"请先登陆后尝试。" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        [_alterLogin show];
        [NSTimer scheduledTimerWithTimeInterval:1.2f target:self selector:@selector(alterLoginAction:) userInfo:nil repeats:YES];
        
        LoginViewController *login = [[LoginViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
        nav.navigationBar.translucent = YES;
        NSDictionary *dic = [NSDictionary dictionaryWithObject:[UIColor redColor] forKey:NSForegroundColorAttributeName];
        nav.navigationBar.titleTextAttributes = dic;
        [self presentViewController:nav animated:YES completion:nil];
        [nav release];
        [login release];
    }
}
#pragma mark - ISSShareViewDelegate
- (void)viewOnWillDisplay:(UIViewController *)viewController shareType:(ShareType)shareType

{
    
    //修改分享编辑框的标题栏颜色
    viewController.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:255 / 255.0 green:69 / 255.0 blue:0 alpha:1];
    
    //将分享编辑框的标题栏替换为图片
    //    UIImage *image = [UIImage imageNamed:@"iPhoneNavigationBarBG.png"];
    //    [viewController.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    
}


- (void)alertAction:(id)sender
{
    [_alert dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)alterLoginAction:(id)sender
{
    [_alterLogin dismissWithClickedButtonIndex:1 animated:YES];
}
//
- (void)locAction:(UIButton *)button
{
    // NSLog(@"loc");
    AttractionsViewController *attraction = [[[AttractionsViewController alloc] init] autorelease];
     NSString *str = [NSString stringWithFormat:@"%d", button.tag];
    attraction.destination_id = str;
    if (str == nil) {
        return;
    }
//    NSLog(@"idid = %ld", button.tag);
    [self.navigationController pushViewController:attraction animated:YES];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
